package com.example.beat_x3.Fragments;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.beat_x3.Client.GetResult;
import com.example.beat_x3.R;

import Entity.Inf;

public class UserFragment extends MyFragment {
    RegisterFragment registerFragment;
    private String account1, password1;
    private TextView account, password;
    private final Handler myHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (Inf.stuInf != null) {
                    Inf.centerFragment = new CenterFragment();
                    changeFragment(Inf.centerFragment);
                    Toast.makeText(Inf.context, Inf.stuInf.StudentAccount, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(Inf.context, "账号或密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_user, null);
        registerFragment = new RegisterFragment();
        account = view.findViewById(R.id.user_account);
        password = view.findViewById(R.id.user_password);
        view.findViewById(R.id.user_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeFragment(registerFragment);
            }
        });

        view.findViewById(R.id.user_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                account1 = account.getText().toString().trim();
                password1 = password.getText().toString().trim();
                if (account1.length() == 0 || password1.length() == 0) {
                    Toast.makeText(Inf.context, "请输入账号或密码", Toast.LENGTH_SHORT).show();
                } else {
                    new LoginTread().start();
                }
            }
        });
        return view;
    }

    class LoginTread extends Thread {
        @Override
        public void run() {
            Inf.stuInf = GetResult.LoginGR(account1, password1);
            if (Inf.stuInf != null) {
                Inf.isLog = true;
                if (Inf.stuInf.BorrowCount > 0) {
                    Inf.credit = 1 - (Inf.stuInf.Defaults * 1.0 / Inf.stuInf.BorrowCount);
                    Inf.COLOR = (int) (Inf.credit * 255);
                }
                myHandler.sendEmptyMessage(1);
            }
        }
    }

}
